package com.mgface.zookeeper;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class Auth {
	private static Logger log = Logger.getLogger(DeleteZnode.class);
	private static ZooKeeper zk = null;

	public static void main(String[] args) throws Exception {
		CountDownLatch cdl = new CountDownLatch(1);
		zk = new ZooKeeper("192.168.244.130:2182", 10_000, e -> {
			log.info("接收到的event:" + e);
			if (e.getState() == KeeperState.SyncConnected) {
				if (e.getType() == EventType.None && e.getPath() == null) {
					cdl.countDown();
				}
			}
		});
		log.info("ZK状态:" + zk.getState().toString());
		Instant start = Instant.now();
		cdl.await();
		Instant end = Instant.now();
		Duration duration = Duration.between(start, end);
		log.info("花费时间:" + duration.toMillis() + "ms");
		log.info("zookeeper session established");
		zk.addAuthInfo("digest", "foo:true".getBytes());
		String _path = zk.create("/zk/5000", "5000".getBytes(), Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);
		log.info("_path="+_path);
		ZooKeeper zk2 = new ZooKeeper("192.168.244.130:2182", 2_000, null);
		Thread.sleep(10_000);
		log.info("结果:"+new String(zk2.getData("/zk/5000", false, null)));
	}

}
